//
//  MemUsed.cpp
//  CollectionTest
//
//  Created by Dusan Vujosevic on 2013-10-26.
//  Copyright (c) 2013 Suavetech. All rights reserved.
//

#include "MemUsed.h"

#ifdef __linux__

#include <fcntl.h>
#include <string.h>
#include <stdlib.h>

int parseLine(char* line)
{
	int i = strlen(line);
	while (*line < '0' || *line > '9') line++;
	line[i-3] = '\0';
	i = atoi(line);
	return i;
}

uint64_t STGetMemUsed()
{
	FILE* file = fopen("/proc/self/status", "r");
	const size_t bufSz = 128;
	char line[bufSz];
	uint64_t result = (uint64_t)-1;
	
	while (fgets(line, bufSz - 1, file) != NULL)
	{
		if (strncmp(line, "VmSize:", 7) == 0)
		{
			result = parseLine(line);
			break;
		}
	}
	fclose(file);
	return result;
}

#else

#include <sys/resource.h>
#include <string.h>

uint64_t STGetMemUsed()
{
	struct rusage ru;
	memset(&ru, 0, sizeof(ru));
	if(getrusage(RUSAGE_SELF, &ru) == 0)
	{
		return (uint64_t)(ru.ru_maxrss/1024);
	}
	else
		return (uint64_t)-1;
}

//#include <mach/vm_statistics.h>
//#include <mach/mach_types.h>
//#include <mach/mach_init.h>
//#include <mach/mach_host.h>
//
//uint64_t STGetMemUsed()
//{
//	vm_size_t page_size;
//	mach_msg_type_number_t count;
//	vm_statistics_data_t vm_stats;
//	
//	mach_port_t mach_port = mach_host_self();
//	if (KERN_SUCCESS == host_page_size(mach_port, &page_size) &&
//		KERN_SUCCESS == host_statistics(mach_port, HOST_VM_INFO,
//										(host_info_t)&vm_stats, &count))
//	{
//		int64_t bytesUsed = ((int64_t)vm_stats.active_count +
//					   (int64_t)vm_stats.inactive_count +
//					   (int64_t)vm_stats.wire_count) *  (int64_t)page_size;
//		return bytesUsed / 1024; // I could >> 10
//	}
//	else
//		return (uint64_t)-1;
//}

#endif

